package com.kim.openfeign.controller;

import com.codingapi.txlcn.tc.annotation.LcnTransaction;
import com.kim.common.resp.CodeMsg;
import com.kim.common.resp.Result;
import com.kim.openfeign.feign.StreamRabbitmqFeign;
import com.kim.openfeign.feign.UserFeign;
import com.kim.redis.lockutil.RedisLockUtil;
import com.kim.user.common.entity.SysUser;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.context.annotation.ScopedProxyMode;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.UUID;

/**
 * @author KimWu
 * @date 2020/5/25 17:31
 * @Description ：
 */
@RestController
@RequestMapping("/feign")
@Slf4j
public class FeignController {

    //分布式锁
    @Autowired
    private RedisTemplate<String, String> redisTemplate;
    @Resource
    private UserFeign userFeign;
    @Resource
    private StreamRabbitmqFeign streamRabbitmqFeign;

    @RequestMapping("/user")
    @HystrixCommand(fallbackMethod = "fallError")
    public Result findByUserName(String username) {
        try {
            Thread.sleep(2500);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        Result<SysUser> byUsername = userFeign.findByUsername(username);
        SysUser result = byUsername.getResult();
        return Result.success(result);
    }

    public Result fallError(String username){
        return Result.error(CodeMsg.METHOD_FALLBACK);
    }

    @RequestMapping("/disLock")
    @LcnTransaction
    public Result test() {
//        try {
            boolean lock = RedisLockUtil.tryGetDistributedLock(redisTemplate, "lock", "1008", 30000);
            if (lock) {
                UUID uuid = UUID.randomUUID();
                String name = "我重名了吗";
                log.info("开始执行 insert user ...");
                Result<String> stringResult = userFeign.userInsert(name);
                log.info("开始执行 insert role ...");
                Result<String> stringResult1 = userFeign.roleInsert(name);
                log.info("开始执行 hello ...");
//                Result<String> hello = streamRabbitmqFeign.hello();
                return Result.success("ok");
            } else {
                log.info(" 未获取到分布式锁 ");
                return Result.error(CodeMsg.ERROR_SYSTEM);
            }
//        }catch (Exception e){
//            log.info("抛出了异常 " + e.getMessage());
//        }
//        return Result.error(CodeMsg.ERROR_SYSTEM);
    }
}
